-- UIRevengeRecords
-- Created by cheny3 Mar/07/2016
-- 复仇记录界面

UIRevengeRecords = class("UIRevengeRecords", function()
    return cc.Layer:create();
end);

function UIRevengeRecords.create()
    return UIRevengeRecords.new();
end

-- 构造函数
function UIRevengeRecords:ctor()
    self:setName("UIRevengeRecords");

    -- 初始化/复用舰长日记界面
    local node = cc.CSLoader:createNode("layout/sky_city/CaptainDiary.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self:init();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 初始化
function UIRevengeRecords:init()
    -- 初始化数据
    self:initRevengeData();

    -- 设置容器高度，加高
    local scrollview = findChildByName(self.node, "CT/scrollview");
    local line1 = findChildByName(self.node, "CT/line1");
    local oriHeight = scrollview:getContentSize().height + 50;
    scrollview:setContentSize(cc.size(scrollview:getContentSize().width, oriHeight));
    line1:setPositionY(line1:getPositionY() + 50);

    -- 记录滚动容器原始宽高
    -- 切换标签页时，滚动容器的内部滚动区域可能会发生变化，因此这里需要将原始宽高记录下来
    scrollview.initInnerHeight = scrollview:getInnerContainerSize().height;
    scrollview.initInnerWidth  = scrollview:getInnerContainerSize().width;
    self.scrollview = scrollview;
end

-- 初始化复仇数据
function UIRevengeRecords:initRevengeData()
    self.revengeList = SkyRelicM.getAllRecords();
end

-- 适配
function UIRevengeRecords:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIRevengeRecords:redraw()
    -- 隐藏TAB节点
    local tabNode = findChildByName(self.node, "CT/tab");
    tabNode:setVisible(false);

    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/title");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, -4);
    titleLabel:setString(getLocStr("revenge_record_title"));

    -- 显示日期
    local dateLabel = findChildByName(self.node, "CT/date");
    TextStyleM.setTextStyle(dateLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_DARK_BROWN);
    local dateStr = os.date("%b.%d", os.time());
    dateLabel:setString(dateStr);

    -- 显示描述
    local descLabel = findChildByName(self.node, "CT/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel:setString(getLocStr("relic_revenge_explain"));

    -- 重绘列表
    self:redrawRevengeList();
end

-- 注册事件处理回调函数
function UIRevengeRecords:registerEventCallback()
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIRevengeRecords 界面析构清理");

            if scrollSchedulerId ~= nil then
                cclog("停止定时器");
                UnSchedule(scrollSchedulerId);
            end
        end
    end);
end

-- 重绘复仇列表
function UIRevengeRecords:redrawRevengeList()
    local scrollview = self.scrollview;
    scrollview:removeAllChildren();
    scrollview:jumpToTop();

    local itemNode = cc.CSLoader:createNode("layout/sky_city/SkyInstanceItem.csb");

    -- 单元格间距(横向)
    local wGap = 0;

    -- 单元格间距(纵向)
    local hGap = 0;

    -- 单元格宽度
    local itemWidth = 0;

    -- 单元格高度
    local itemHeight = 61;

    -- 左右留白
    local leftMargin = 1;

    -- 上方留白
    local topMargin = 10;

    -- 下方留白
    local bottomMagin = 0;

    -- 单页最大可容纳行数
    local pageRowNum = 8;

    -- 单页最大可容纳列数
    local pageColNum = 1;

    -- 获取记录总数
    local totalNum = #self.revengeList;

    -- 初始化滚动容器
    ScrollTool.initScrollGridsVertical(self, scrollview, itemNode, totalNum,
        pageColNum, wGap, hGap,
        itemWidth, itemHeight, topMargin, bottomMagin, leftMargin,
        self.registerItemTouchEvent, self.initRevengeItem);

    -- 如果超过一页
    if totalNum > pageRowNum then
        -- 添加滑块
        UIIndicator.attach(scrollview);
    end
end

-- 注册滚动容器每一行被点击的事件
function UIRevengeRecords:registerItemTouchEvent(node)
    local touchImg = findChildByName(node, "touch_bg");
    local goImg   = findChildByName(node, "go");
    local oriScale = goImg:getScale();
    touchImg:setOpacity(0);
    local function onBgClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.began then
            if sender == goImg then
                goImg:setScale(oriScale - 0.1);
            end
        elseif eventType == ccui.TouchEventType.canceled then
            if sender == goImg then
                goImg:setScale(oriScale);
            end
        elseif eventType == ccui.TouchEventType.ended then
            if sender == goImg then
                goImg:setScale(oriScale);
            end
            self:onChildClick(node);
            AudioM.playFx("button_caption");
        end
    end
    touchImg:addTouchEventListener(onBgClick);
    goImg:addTouchEventListener(onBgClick);
end

-- 项目被点击的处理
function UIRevengeRecords:onChildClick(child)
    if not SkyRelicM.isValidRecord(child.recordRid) then
        -- 记录已经失效
        alert(getLocStr("revenge_record_unvalid"));
        self:redraw();
        return;
    end
    -- 播放录像
    SkyRelicM.playVideo(child.recordRid);
end

-- 初始化项目
function UIRevengeRecords:initRevengeItem(child, index)
    local revengeInfo = self.revengeList[index];
    child.recordRid = revengeInfo["record_rid"];

    local iconImg = findChildByName(child, "icon");
    local goImg   = findChildByName(child, "go");
    local statusLabel = findChildByName(child, "status");
    local nameLabel = findChildByName(child, "desc");
    local timeLabel = findChildByName(child, "time");

    -- 国籍
    iconPath = TopM.queryNationality(revengeInfo["nation"], "icon");
    iconImg:loadTexture(getNationalityIconPath(iconPath));

    -- 玩家名字
    nameLabel:setString(getNickName(revengeInfo["name"]));
    nameLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL);
    local color = TextStyleM.TEXT_COLOR_DARK_RED;
    if revengeInfo["result"] == 0 then
        -- 防守成功
        color = TextStyleM.TEXT_COLOR_BLUE;
    end
    nameLabel:setTextColor(color);

    -- goimg 更换录像图标
    goImg:loadTexture(getSkyCityRuinsIconPath("record"));
    statusLabel:setVisible(false);

    -- 距离被抢过去的时间
    local durTime = TimeM.getServerTime() - revengeInfo["strike_time"];
    local timeStr = self:analysisTimeStr(durTime);

    timeLabel:setString(string.format(getLocStr("rob_time_tip"), timeStr));
    timeLabel:setFontSize(TextStyleM.TEXT_SIZE_SMALL);
    timeLabel:setTextColor(TextStyleM.TEXT_COLOR_GRAY);
    timeLabel:setVisible(true);

    -- 如果是第一条记录，需要显示上部的分隔线
    local lineTop = findChildByName(child, "line2");
    if index == 1 then
        lineTop:setVisible(true);
    else
        lineTop:setVisible(false);
    end

    return child;
end

-- 时间格式
function UIRevengeRecords:analysisTimeStr(leftTime)
    if leftTime > 86400 then
        return math.floor(leftTime/86400) .. "d";
    elseif leftTime > 3600 then
        return math.floor(leftTime/3600) .. "h";
    elseif leftTime > 60 then
        return math.floor(leftTime/60) .. "m";
    end
    return math.floor(leftTime) .. "s";
end

-- 注册点击事件
function UIRevengeRecords:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIRevengeRecords");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end
